<script setup>
import { ref, onMounted } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import defaultAvatar from '@/assets/avatar.jpg'
import { ElMessage } from 'element-plus'
import { useSetAvatarService } from '@/api/request.js'
import { useUserStore } from '@/stores/index.js'

const userStore = useUserStore()

const disable = ref(true)
const isLoadling = ref(false)
const imgUrl = ref('')

onMounted(() => {
  imgUrl.value = userStore.user.user_pic
})
const handleChange = (uploadFile) => {
  console.log(uploadFile.raw)
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  disable.value = false
}

const checkType = (uploadFile) => {
  console.log('check', uploadFile)
  if (uploadFile.type !== 'image/jpeg') {
    ElMessage.error('文件格式错误！')
    imgUrl.value = defaultAvatar
    return false
  } else if (uploadFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的文件大小要在2MB内')
    imgUrl.value = defaultAvatar
    return false
  }

  return true
}

function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
    reader.readAsDataURL(file)
  })
}

const show = async () => {
  // 通过url加载图片数据
  const avatar = await fetch(imgUrl.value)
  // 将图片数据转换为 blob
  const blob = await avatar.blob()
  // 利用 blob对象 创建 基于 url 的图片File对象
  const file = new File([blob], imgUrl.value, { type: blob.type })
  const base64 = await fileToBase64(file)
  console.log(base64)

  isLoadling.value = true
  await useSetAvatarService({ avatar: base64 })
  await userStore.saveUserInfo()
  disable.value = true
  isLoadling.value = false

  ElMessage.success('头像更新成功')
}
</script>

<template>
  <div class="change-avatar">
    <PageContainer title="更换头像">
      <template #main>
        <el-upload
          action="#"
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="handleChange"
          :before-upload="checkType"
        >
          <img v-if="true" :src="imgUrl || defaultAvatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          <div class="button">
            <el-button type="primary">选择头像</el-button>
            <el-button
              :disabled="disable"
              type="success"
              @click.prevent.stop="show"
              :loading="isLoadling"
              >上传头像</el-button
            >
          </div>
        </el-upload>
      </template>
    </PageContainer>
  </div>
</template>

<style lang="scss">
//.avatar-uploader .el-upload {
//  border: 1px dashed var(--el-border-color);
//  border-radius: 6px;
//  cursor: pointer;
//  position: relative;
//  overflow: hidden;
//  transition: var(--el-transition-duration-fast);
//}

//.el-upload.el-upload--text {
//  width: 400px !important;
//  height: 400px !important;
//  display: flex;
//  flex-direction: column;
//  align-items: center;
//  justify-content: center;
//}

//.avatar-uploader .el-upload:hover {
//  border-color: var(--el-color-primary);
//}

.avatar-uploader .el-upload {
  width: 450px !important;
  height: 450px !important;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-evenly;
}

.avatar-uploader .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 300px;
  height: 300px;
}
</style>
